package com.george.controller;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.george.entity.Result;
import com.george.entity.StatusCode;
import com.george.model.entity.User;
import com.george.service.IUserService;
import com.george.util.IdWorker;
import com.george.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author George Chan
 * @since 2019-09-28
 */
@RestController
@CrossOrigin // 跨域
@RefreshScope // 刷新配置
@RequestMapping("/api/user")
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 程序端口
    @Value("${server.port}")
    private String port;
    // 生成token的key
    @Value("${server.port}")
    private String jwtKey;
    // token过期时长（毫秒）
    @Value("${server.port}")
    private int jwtTtl;

    private final IUserService userService;
    private final IdWorker idWorker;
    private final JwtUtil jwtUtil;
    private final BCryptPasswordEncoder encoder;

    @Autowired
    public UserController(IUserService userService, IdWorker idWorker, JwtUtil jwtUtil, BCryptPasswordEncoder encoder) {
        this.userService = userService;
        this.idWorker = idWorker;
        this.jwtUtil = jwtUtil;
        this.encoder = encoder;
    }

    @GetMapping("/port")
    public String getPort() {
        return this.port;
    }

    @GetMapping("/user/{id}")
    public Object list(@PathVariable int id) {
        User user = userService.findById(id);
        return JSON.toJSONString(user);
    }

    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        if (ObjectUtil.isNull(user)) {
            return new Result(false, StatusCode.ERROR, "操作失败！");
        }
        logger.info("保存用户对象为 ====》  {}", JSON.toJSONString(user));
        user.setId(idWorker.nextId());
        user.setPassword(encoder.encode(user.getPassword()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        boolean res = userService.save(user);
        if (!res) {
            return new Result(false, StatusCode.ERROR, "操作失败！");
        }
        return new Result(true, StatusCode.OK, "操作成功！");
    }
}

